import { Md5 } from "ts-md5";

const HEX_LIST = [
    '0', '1', '2', '3',
    '4', '5', '6', '7',
    '8', '9', 'A', 'B',
    'C', 'D', 'E', 'F',
];

export function u16toHex(value: number) {
    const v0 = HEX_LIST[(value >> 12) & 0x0F];
    const v1 = HEX_LIST[(value >> 8) & 0x0F];
    const v2 = HEX_LIST[(value >> 4) & 0x0F];
    const v3 = HEX_LIST[value & 0x0F];
    return `${v0}${v1}${v2}${v3}`;
}

export function u32toHex(value: number) {
    const v0 = u16toHex(value >> 16);
    const v1 = u16toHex(value & 0xFFFF);
    return `${v0}${v1}`;
}

export function u8toHex(value: number) {
    const v2 = HEX_LIST[(value >> 4) & 0x0F];
    const v3 = HEX_LIST[value & 0x0F];
    return `${v2}${v3}`;
}

export function toHex(value: number[]) {
    let s = '';
    for (let v of value) {
        s += u8toHex(v);
        s += ' ';
    }
    return s;
}

export function md5Sum(buf: Uint8Array) {
    const md5 = new Md5();
    md5.appendByteArray(buf);
    const i32buf = md5.end(true);
    return new Uint8Array((i32buf as Int32Array).buffer);
}
